﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Collections.Generic;
using System.Diagnostics;

namespace Fav {

    public class MasonryView {
        private ListBox parent;
        private int columns;
        private double margin;

        private StackPanel rootPanel;


        public MasonryView(ListBox parent, int columns = 3, double margin = 8) {
            if (columns < 1) {
                columns = 1;
            }
            this.parent = parent;
            this.columns = columns;
            this.margin = margin;

            rootPanel = new StackPanel();
            rootPanel.Orientation = Orientation.Horizontal;

             parent.Items.Add(rootPanel);

            for (int i = 0; i < columns; ++i) {
                var panel = new StackPanel();
                rootPanel.Children.Add(panel);
            }
            remeasure();
        }


        public void AddItem(FrameworkElement el) {
            StackPanel sp = (StackPanel)rootPanel.Children[0];
            double n = Double.MaxValue;
 
            foreach (StackPanel p in rootPanel.Children) {
                double height = 0;
                foreach (FrameworkElement r in p.Children) {
                    height += r.ActualHeight;
                }
                if (height < n) {
                    n = height;
                    sp = p;
                }
            }
            double aspect = 0;
            if (el.ActualWidth > 0) {
                aspect = el.ActualHeight / el.ActualWidth;
            } else {
                aspect = el.Height / el.Width;
            }
            el.Width = sp.ActualWidth;
            el.Height = el.Width * aspect;
            el.Margin = new Thickness(0, 0, 0, margin);

            sp.Children.Add(el);
            sp.UpdateLayout();
        }

        public void ClearItems() {
            foreach (StackPanel p in rootPanel.Children) {
                p.Children.Clear();
            }
            parent.UpdateLayout();
        }


        private void remeasure() {
            double colWidth = (parent.ActualWidth-((columns-1)*margin)) / columns;

            int n = 0;
            foreach (StackPanel p in rootPanel.Children) {
                p.Width = colWidth;
                if (n++ > 0) {
                    p.Margin = new Thickness(margin, 0, 0, 0);
                }
            }
            parent.UpdateLayout();
        }
    }
}
